<?php
  require_once "DB.php";
  include_once("./libraries/authentication.inc.php");
  include_once("./libraries/db.inc.php");
  
  session_start();
 
  sessionAuthenticate("login.php");

  $connection = DB::connect($dsn, $options);
  if (DB::isError($connection)) {
    trigger_error($connection->getMessage(), E_USER_ERROR);
  }

  //register and clear our errors array
  if (isset($_SESSION["pwdErrors"])) {
    unset($_SESSION["pwdErrors"]);
  }
  $_SESSION["pwdErrors"] = array();

  //set up an array for the POST vars
  $_SESSION["chgPwdFormVars"] = array();

  $_SESSION["chgPwdFormVars"]["Orig"] = $_POST["chgPassOrig"];
  $_SESSION["chgPwdFormVars"]["New1"] = $_POST["chgPassNew1"];
  $_SESSION["chgPwdFormVars"]["New2"] = $_POST["chgPassNew2"];

  if(strlen($_SESSION["chgPwdFormVars"]["New1"]) == 0) {
    $_SESSION["pwdErrors"]["New1"] = "You did not type in a new password.";
  }
  elseif($_SESSION["chgPwdFormVars"]["New1"] != $_SESSION["chgPwdFormVars"]["New2"]) {
    $_SESSION["pwdErrors"]["New1"] = "Passwords must match EXACTLY.";
  }
  elseif($_SESSION["chgPwdFormVars"]["New1"] == $_SESSION["chgPwdFormVars"]["Orig"]) {
    $_SESSION["pwdErrors"]["New1"] = "The password must change.";
  }

  if(!authenticateUser($_SESSION["loginUsername"],
                       $_SESSION["chgPwdFormVars"]["Orig"],
                       $connection)) {
    $_SESSION["pwdErrors"]["Orig"] = "The current password you entered is incorrect.";
  }

  if(count($_SESSION["pwdErrors"]) > 0) {
    //try again...
    header("Location: changePassword.php");
    $connection->disconnect();
    exit;
  }

  //hooray! we made it, now put it into the database

  $crypted_pword = md5(trim($_SESSION["chgPwdFormVars"]["New1"]));
 
  $sql = "UPDATE cdb_users SET password = '{$crypted_pword}' " .
         "WHERE username = '{$_SESSION["loginUsername"]}';";
  
  $result = $connection->query($sql);

  if(DB::isError($result)) {
    trigger_error($result->getMessage(), E_USER_ERROR);
  }

  //clear out the variables
  unset($_SESSION["chgPwdFormVars"]);
  unset($_SESSION["pwdErrors"]);

  $_SESSION["message"] = "Your password has been successfully changed.";

  header("Location: changePassword.php");
  $connection->disconnect();  
?>
